"""
serializers
Administrator
2023/12/6
convergence-server
"""
import re
from rest_framework import serializers
from .models import MediaContent, Image, Label, AccountBindMediaContent, ContentType
from platefrom.models import SkusUser,Platefrom,Skus
from user.models import User,UserAccountBind
from rest_framework.fields import SerializerMethodField
from platefrom.serializers import PlatformSerializer
from user.serializers import UserAccountBindSerializer
from server.utils import  check_group_id

class MediasSerializer(serializers.ModelSerializer):
    """用户发布内容"""

    class Meta:
        model = MediaContent
        fields = "__all__"

    def create(self, validated_data):
        # 普通用户
        skus = {}
        req_data = self.context['request'].data
        user_group_id = self.context['request'].user.group_id
        if req_data.get('skus_id') and req_data['skus_id'] != 1:
            if check_group_id(user_group_id) == 'person':
                validated_data['types'] = 'distribute'
                skus = SkusUser.objects.filter(user_id=self.context['request'].user.id).first()
                validated_data['skus_id'] = skus.skus_id
            # 获取公司的套餐
            elif check_group_id(user_group_id) == 'staff':
                validated_data['types'] = 'checking'
                user = User.objects.filter(id=self.context['request'].user.id).first()
                skus = SkusUser.objects.filter(company_id=user.company_id).first()
                validated_data['skus_id'] = skus.skus_id
            elif check_group_id(user_group_id) == 'company_admin':
                validated_data['types'] = 'checking'
                user = User.objects.filter(id=self.context['request'].user.id).first()
                skus = SkusUser.objects.filter(company_id=user.company_id).first()
                validated_data['skus_id'] = skus.skus_id

            if type(validated_data['label']) == 'list':
                validated_data['label'] = ','.join(validated_data['label'])
            validated_data['creator_user_id'] = self.context['request'].user.id

            # 查询套餐内容
            skus = Skus.objects.filter(id=skus.skus_id).first()
            # 套餐里面的平台
            platefroms = Platefrom.objects.filter(id__in=skus.platefrom_ids.split(',')).values()
            validated_data['platefroms_id'] = skus.platefrom_ids
            validated_data['accounts_mobiles'] = ",".join(req_data['accounts'])
            instance = MediaContent.objects.create(**validated_data)


            #  普通用户直接进行分发
            if check_group_id(user_group_id) == 'person':
                # 向AccountBindMediaContent 添加数据

                for account in req_data['accounts']:
                    for platefrom in platefroms:
                        account_bind_media_content = AccountBindMediaContent()
                        account_bind_media_content.status = 0
                        account_bind_media_content.media_title = instance.title
                        account_bind_media_content.media_desc = instance.desc
                        account_bind_media_content.platform_name = platefrom['en_name']
                        account_bind_media_content.url = validated_data['media']
                        account_bind_media_content.media_content_in_platform_id = platefrom['id']
                        account_bind_media_content.account_id = validated_data['creator_user_id']
                        account_bind_media_content.media_content_id = instance.id

                        # account = UserAccountBind.objects.filter(user_id=validated_data['creator_user_id'],
                        #                                          platefrom_id=platefrom['id']).first()
                        if account:
                            account_bind_media_content.account = account
                            account_bind_media_content.android_login_file = ''
                            account_bind_media_content.save()

        else:
            validated_data['skus_id'] = '1'
            if check_group_id(user_group_id) == 'person':
                validated_data['types'] = 'distribute'
                # 获取公司的套餐
            elif check_group_id(user_group_id) == 'staff':
                validated_data['types'] = 'checking'

            elif check_group_id(user_group_id) == 'company_admin':
                validated_data['types'] = 'checking'

            if type(validated_data['label']) == 'list':
                validated_data['label'] = ','.join(validated_data['label'])
            validated_data['creator_user_id'] = self.context['request'].user.id

            if len(req_data['platefroms']) > 0:
                validated_data['platefroms_id'] = ','.join(str(num) for num in req_data['platefroms'])
            else:
                validated_data['platefroms_id'] = ''
            instance = MediaContent.objects.create(**validated_data)

            #  普通用户直接进行分发
            if check_group_id(user_group_id) == 'person':

                # 没有套餐--用户上传的平台
                # 向AccountBindMediaContent 添加数据

                accounts = UserAccountBind.objects.filter(id__in=req_data['accounts']).values()
                for account in accounts:
                    account_bind_media_content = AccountBindMediaContent()
                    account_bind_media_content.status = 0
                    account_bind_media_content.media_title = instance.title
                    account_bind_media_content.media_desc = instance.desc
                    account_bind_media_content.platform_name = account['en_name']
                    account_bind_media_content.url = validated_data['media']
                    account_bind_media_content.media_content_in_platform_id = account['platefrom_id']
                    account_bind_media_content.account_id = validated_data['creator_user_id']
                    account_bind_media_content.media_content_id = instance.id
                    account_bind_media_content.account = account['plate_account']
                    account_bind_media_content.android_login_file = account['app_account_upload']
                    account_bind_media_content.save()


        return  instance


    def update(self, instance, validated_data):
        MediaContent.objects.filter(pk=instance.pk).update(**validated_data)
        return instance


class ImageSerializer(serializers.ModelSerializer):
    """图库"""

    class Meta:
        model = Image
        fields = ('id', 'image_label', 'title', 'image', 'is_image')

    def create(self, validated_data):
        validated_data['creator_user_id'] = self.context['request'].user.id
        instance = Image.objects.create(**validated_data)
        return instance


class VideoSerializer(serializers.ModelSerializer):
    """视频库"""

    class Meta:
        model = Image
        fields = ('id', 'image_label', 'title', 'image', 'is_image')
        depth = 2

    def create(self, validated_data):
        instance = Image.objects.create(**validated_data)
        return instance


class LabelSerializer(serializers.ModelSerializer):
    """媒体标签"""
    platform = PlatformSerializer(read_only=True)

    class Meta:
        model = Label
        fields = "__all__"


class MediaContentSerializer(serializers.ModelSerializer):
    """媒体文件序列化器"""
    label = LabelSerializer(read_only=True, many=True)

    class Meta:
        model = MediaContent
        fields = "__all__"


class AccountBindMediaContentSerializer(serializers.ModelSerializer):
    """媒体文件-账号 序列化器"""
    account = UserAccountBindSerializer(read_only=True)
    media_content = MediaContentSerializer(read_only=True)

    class Meta:
        model = AccountBindMediaContent
        fields = "__all__"


class ContentTypeSerializer(serializers.ModelSerializer):
    """
    迪：通用标签类型
    """

    class Meta:
        model = ContentType
        fields = ('id', 'type')
